package com.icesoft.core.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Created by MaiDiAo on 2019-04-22
 *
 * @Version: 1.0
 * @see
 * @since 1.0
 */
@Slf4j
public class GZIPUtils {

    /**
     * GZIP压缩
     *
     * @param source 源数组
     * @return 压缩数组
     * @throws Exception
     */
    public static byte[] compress(byte[] source) {
        if (source == null || source.length == 0) {
            return source;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(source);
            gzip.close();
        } catch (IOException e) {
            log.error("", e);
        }
        return out.toByteArray();
    }

    /**
     * GZIP解压
     *
     * @param cipher 压缩字节数组
     * @return 源数组
     * @throws IOException 
     * @throws Exception
     */
    public static byte[] uncompress(byte[] cipher) throws IOException  {
        if (cipher == null || cipher.length == 0) {
            return cipher;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(cipher);
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[1024];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        gunzip.close();
        return out.toByteArray();
    }


}
